﻿using System;
using System.Collections;
using System.IO;
using System.Net.Mail;
using System.Text;

using NVelocity;
using NVelocity.App;

using Yawf.Core;
using Yawf.Core.Utils;

namespace Yawf.Web.Mail {
	public class MailService {
		private SmtpClient mailSender = new SmtpClient("localhost");
		private VelocityEngine engine;

		public SmtpClient MailSender { get { return mailSender; } set { mailSender = value;} }
		public VelocityEngine Engine { get { return engine; } set { engine = value; } }

		/// <summary>
		/// Sends a mail
		/// </summary>
		/// <param name="springName">Name of Spring Mail object</param>
		/// <param name="model">Model to use for creating body content of mail</param>
		public void Send(String springName, Hashtable model) {
			Mail mail;

			mail = Initializer.Instance.GetObject(springName) as Mail;
			Send(mail, model);
		}

		/// <summary>
		/// Sends a mail
		/// </summary>
		/// <param name="mail">Mail object with mail data</param>
		/// <param name="model">Model to use for creating body content of mail</param>
		public void Send(Mail mail, Hashtable model) {
			MailMessage message;
			VelocityContext context;
			StringWriter writer;

			// Create Message
			message = new MailMessage(mail.From,mail.To);
			if (!StringUtils.IsEmpty(mail.Cc)){
				message.CC.Add(mail.Cc);
			}
			if (!StringUtils.IsEmpty(mail.Cc)){
				message.Bcc.Add(mail.Bcc);
			}
			message.Subject = mail.Subject;
			message.BodyEncoding = Encoding.UTF8;
			message.IsBodyHtml = mail.IsHtml;

			// Use Velcoity to create Body
			context = new VelocityContext(model);
			writer = new StringWriter();
			engine.MergeTemplate(mail.Template, Encoding.UTF8.WebName, context, writer);
			message.Body = writer.ToString();

			if (mail.DoSendAsync) {
				MailSender.SendAsync(message, null);
			} else {
				MailSender.Send(message);
			}
		}
	}
}
